<template>
  <div>
    <el-select
      v-select-scroll="!collapseTags"
      ref="selectRef"
      v-model="selectData"
      :disabled="disabled"
      :filterable="filterable"
      :filter-method="createNew ? createNewFilterMethod : filterMethod"
      :remote-method="remoteMethod"
      :remote="remote"
      :multiple="multiple"
      :collapse-tags="collapseTags"
      :placeholder="placeholder"
      :clearable="clearable"
      :size="size"
      :allow-create="allowCreate"
      :popper-append-to-body="popperAppendToBody"
      :value-key="valueType==='object'?keyName:''"
      :popper-class="'global-select-down '+ extendClass + createNewClass"
      class="filterableSelect remoteRequestClient select-component-withouthttp"
      @focus="$emit('selectWithoutHttpFocus')"
      @visible-change="visibleChanges"
      @change="changeinfo"
      @clear="$emit('clear', $event)">
      <el-option v-if="addNew" :value="-9999" class="select-extend-btn" disabled>
        <div class="select-extend-btn-text" @click="handleAddNew">{{ addNewStr }}</div>
      </el-option>
      <template v-if="defaultList">
        <el-option
          v-for="item in defaultList"
          :key="item[keyName]+'default'"
          :label="getLabel(item)"
          :value="valueType==='object'?item:item[keyName]"
          style="display:none;"/>
      </template>
      <el-option
        v-for="item in dataOptions"
        :key="item[keyName]"
        :style="itemMaxWidth > 0?{maxWidth:itemMaxWidth+'px !important'}:''"
        :label="getLabel(item)"
        :disabled="item.disabled"
        :value="valueType==='object'?item:item[keyName]" >
        <div class="check-user-container">
          <tipIcon v-if="tipKey" :content="item[tipKey] || '--'" class="mr5"/>
          <Ellipsis :content="getLabel(item)" :tooltip="item[showToolTip]" :placement="placement" class="label" />
          <CheckUserInfo v-if="showCheckUser" :user-id="item[keyName]" style="margin-right: 4px;" />
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String | Number,
      default: ''
    },
    defaultList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    listData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    size: {
      type: String,
      default: 'small'
    },
    showToolTip: {
      type: String,
      default: ''
    },
    placement: {
      type: String,
      default: 'left'
    },
    delay: {
      type: Number,
      default: 800
    },
    disabled: {
      type: Boolean,
      default: false
    },
    labelName: { // label的字段
      type: String,
      default: 'value'
    },
    keyName: { // key的字段
      type: String,
      default: 'id'
    },
    multiple: { // 多选
      type: Boolean,
      default: false
    },
    filterable: { // 是否开启搜索
      type: Boolean,
      default: false
    },
    collapseTags: { // 折叠tag
      type: Boolean,
      default: false
    },
    clearable: { // 是否可以清除
      type: Boolean,
      default: false
    },
    remote: {
      type: Boolean,
      default: false
    },
    itemMaxWidth: {
      type: Number,
      default: 0
    },
    remoteMethod: {
      type: Function,
      default: null
    },
    valueType: { // 如果值为object,则值使用对象传输
      type: String,
      default: ''
    },
    extendClass: {
      type: String,
      default: ''
    },
    popperAppendToBody: {
      type: Boolean,
      default: true
    },
    addNew: { // 下拉框第一个点击事件，目前用于添加新的供应商
      type: Boolean,
      default: false
    },
    addNewStr: {
      type: String,
      default: '添加新供应商'
    },
    allowCreate: {
      type: Boolean,
      default: false
    },
    filterMethod: {
      type: Function,
      default: null
    },
    unitParams: {
      type: Object,
      default: null
    },
    showCheckUser: {
      type: Boolean,
      default: false
    },
    tipKey: {
      type: String,
      default: ''
    },
    createNew: { // 是否可以在当前页面新建下拉项，比如新建银行
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dataOptions: []
    };
  },
  computed: {
    createNewClass() {
      return this.createNew ? 'create-new-select' : '';
    },
    selectData: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('change', val);
      }
    }
  },
  watch: {
    'listData': {
      handler(val) {
        this.dataOptions = _.cloneDeep(val);
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    createNewFilterMethod(val) {
      const bkpRef = this.$refs.selectRef;
      let popper = bkpRef.$refs.popper;
      if (popper.$el) popper = popper.$el;
      if (val) {
        // 本地过滤，防止组件重新渲染导致搜索失效
        this.dataOptions = this.listData.filter(it => it.name.includes(val));
        if (!this.dataOptions.length) {
          const innerHtmlStr = `
                  <el-option :value="${val}">
                    <div style="display: flex;justify-content: space-between;">
                      <div class="ellipsisOne" style="flex: 1;height: 18px;">${val}</div>
                      <div @click="createNewItem" style="color: #406EFF;cursor: pointer;width: 40px;text-align: right;">
                        新建
                      </div>
                    </div>
                  </el-option>`;
          if (!Array.from(popper.children).some(v => v.className === 'create-new-select-item')) {
            const el = document.createElement('div');
            el.className = 'create-new-select-item';
            el.innerHTML = innerHtmlStr;
            popper.appendChild(el);
            el.onclick = () => {
              this.createNewItem(val);
            };
          } else {
            const el = document.querySelector('.create-new-select-item');
            el.innerHTML = innerHtmlStr;
            el.onclick = () => {
              this.createNewItem(val);
            };
          }
        } else {
          this.removeAddNewElement();
        }
      } else {
        this.removeAddNewElement();
        this.dataOptions = _.cloneDeep(this.listData);
      }
    },
    createNewItem(val) {
      this.$emit('createNewItem', val);
    },
    removeAddNewElement() {
      const el = document.querySelector('.create-new-select-item');
      if (el) {
        el.parentNode.removeChild(el);
      }
    },
    visibleChanges(e) {
      this.$emit('visible-changes', e);
    },
    changeinfo(id) {
      if (this.createNew) {
        // 本地过滤时重置下拉项
        this.dataOptions = _.cloneDeep(this.listData);
      }
      if (typeof id !== 'object') {
        const item = this.listData.find(i => i.id === id);
        this.$emit('changeInfo', item);
      } else {
        this.$emit('changeInfo', id);
      }
    },
    handleAddNew() {
      this.$emit('addNewClick');
    },
    getLabel(item) {
      const unitParams = this.unitParams;
      if (unitParams && unitParams.field && item[unitParams.field]) {
        return item[this.labelName] + `（${item[unitParams.field]}）`;
      }
      return item[this.labelName];
    }
  }
};
</script>

<style lang="scss" scoped>
.select-component-withouthttp {
  &::v-deep {
    .filterableSelect {
      width: 100%;
    }
    .el-select__tags{
      margin-top: 0px;
    }
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
      // overflow: hidden;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      display: flex;
      align-items: center;
      .el-tag__close {
        right: 0;
        margin: 0 0 0 3px;
      }
    }
  }
}
.select-extend-btn {
  cursor: pointer;
  border-bottom: 1px solid #ddd;
  .select-extend-btn-text {
    color: #406eff;
    cursor: pointer;
  }
}
.check-user-container {
  display: flex;
  align-items: center;
  .label {
    flex: 1;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>
<style lang="scss">
.create-new-select {
  .el-select-dropdown__empty {
    display: none;
  }
  .create-new-select-item {
    font-size: 14px;
    height: 34px;
    color: #606266;
    line-height: 14px;
    padding: 10px 8px;
    cursor: pointer;
    max-width: 241px;
  }
}
</style>
